package com.siashan.toolkit.sms.core;

import com.siashan.toolkit.sms.cache.SmsCacheTemplate;
import com.siashan.toolkit.sms.core.entity.*;
import com.siashan.toolkit.sms.core.executor.SmsSendExecutor;
import lombok.Getter;
import lombok.Setter;

import java.util.Collection;

/**
 * 抽象短信模板类
 *
 * @author siashan
 * @since v1.0.6
 **/
@Setter
@Getter
public class AbstractSmsTemplate {

    private SmsCacheTemplate smsCacheTemplate;
    private SmsSendExecutor smsSendExecutor;

    public AbstractSmsTemplate(SmsCacheTemplate smsCacheTemplate, SmsSendExecutor smsSendExecutor) {
        this.smsCacheTemplate = smsCacheTemplate;
        this.smsSendExecutor = smsSendExecutor;
    }

    /**
     * 发送通知
     *
     * @param smsSendModel 通知内容
     * @param phone        手机号
     * @return 是否发送成功
     */
    public SmsSendResult send(SmsModel smsSendModel, String phone) {
        boolean send = smsSendExecutor.send(smsSendModel, phone);
        return SmsSendResult.sendResult(send);
    }

    /**
     * 发送短信
     *
     * @param model 参数
     * @param phones 手机号
     */
    public SmsSendResult send(SmsModel model, Collection<String> phones) {
        boolean send = smsSendExecutor.send(model, phones);
        return SmsSendResult.sendResult(send);
    }

    /**
     * 发送短信验证码
     *
     * @param verifyData 短信验证码内容
     * @param phone      手机号
     * @return 是否发送成功
     */
    public SmsSendResult send(SmsVerifyModel verifyData, String phone) {
        SmsSendResult sendResult = null;
        SmsFrequencyLimitConfig frequencyLimitConfig = smsSendExecutor.getFrequencyLimitConfig();
        SmsWhiteList whiteList = smsSendExecutor.getWhiteList();
        SmsFrequencyResult smsFrequencyResult = smsCacheTemplate.preCheck(verifyData, phone,frequencyLimitConfig,whiteList);
        if (smsFrequencyResult.canSend()) {
            boolean send = smsSendExecutor.send(verifyData, phone);
            if (send) {
                smsCacheTemplate.put(phone, verifyData.getSmsCode(), verifyData.getExpireTimeout());
            }
            sendResult = SmsSendResult.sendResult(send);
        } else {
            sendResult = SmsSendResult.frequnecyCheckFail(smsFrequencyResult);
        }
        return sendResult;
    }





    /**
     * 校验短信验证码
     *
     * @param key   验证码key
     * @param value 验证码
     * @return SmsVerifyCkResult
     */
    public SmsVerifyCheckResult validate(String key, String value) {
        String sv = smsCacheTemplate.get(key);
        smsCacheTemplate.release(key);
        if (null == sv || "".equals(sv.trim())) {
            return SmsVerifyCheckResult.empty();
        }
        if (sv.equalsIgnoreCase(value)) {
            return SmsVerifyCheckResult.success();
        } else {
            return SmsVerifyCheckResult.fail();
        }
    }
}
